package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.entity.MessageConstant;
import com.itheima.entity.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("/member")
public class MemberController {

    @Autowired
    private JedisPool jedisPool;

    @Reference
    private MemberService memberService;

    @RequestMapping("/login")
    public Result login(HttpServletRequest request ,HttpServletResponse response , @RequestBody Map map){

        //设置短时间内的访问次数限制
        String ip = request.getRemoteAddr();
        Jedis resource = jedisPool.getResource();
        String count = resource.get(ip);

        if(count != null){

            int countInt = Integer.parseInt(count);
            if(countInt>3){
                return new Result(false,"访问次数受限");
            }
            resource.setex(ip,60,countInt+1+"");
        }else {
            resource.setex(ip,60,1+"");
        }

        //获得验证码和号码
        String telephone = (String) map.get("telephone");
        String validateCode = (String) map.get("validateCode");

        //从redis中获取验证码

        String validateCodeInRedis = resource.get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);

        //比较
        if(validateCode != null && validateCodeInRedis != null && validateCode.equals(validateCodeInRedis)){
            //验证码输入成功
            //判断该用户是否是会员
            Member member = memberService.findByPhoneNumber(telephone);
            if(member == null){
                //不是会员,把他注册成会员
                member = new Member();
                member.setPhoneNumber(telephone);
                member.setRegTime(new Date());
                memberService.add(member);
            }

            //把账号放入cookie中
            Cookie cookie = new Cookie("mtc", telephone);
            cookie.setPath("/");
            cookie.setMaxAge(60*60*24*30);
            response.addCookie(cookie);

            //把member添加进redis中
            String json = JSON.toJSON(member).toString();
            resource.setex(telephone,60*30,json);
            resource.close();
            return new Result(true,MessageConstant.LOGIN_SUCCESS);
        }else{
            //验证码输入错误
            resource.close();
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }



    }


}
